package com.example.back.mapper;

import com.example.back.entity.Comment;
import com.example.back.entity.otd.CommentDTO;
import org.apache.ibatis.annotations.*;

import java.util.ArrayList;
import java.util.List;

@Mapper
public interface CommentMapper {
    @Insert("insert into comment(userId, useredId, text, time, url, postId, parentId) " +
            "values(#{userId}, #{useredId}, #{text}, #{time}, #{url}, #{postId}, #{parentId})")
    int addComment(Comment comment);
    @Delete("delete from comment where id=#{id}")
    int deleteComment(Integer id);
    @Update("update comment set userId=#{userId},useredId=#{useredId},text=#{text},time=#{time},url=#{url} where id=#{id}")
    int updateComment(Comment comment);
    @Select("select * from comment where id=#{id}")
    Comment queryCommentById(Integer id);
    @SelectProvider(type = CommentMapperProvider.class, method = "getQueryCommentsSql")
    ArrayList<Comment> queryComments(Comment comment);

    //============= 查询某个帖子的所有评论 ==============
    // 查询某个帖子的所有评论（带评论者信息）
    @Select("SELECT " +
            "  c.id AS commentId, " +
            "  c.text AS commentContent, " +
            "  c.time AS commentTime, " +
            "  u.tx AS avatar, " +
            "  u.nc AS nickname, " +
            "  c.userId AS userId "+
            "FROM " +
            "  comment c " +
            "JOIN " +
            "  user u ON c.userId = u.id " +
            "WHERE " +
            "  c.postId = #{postId} " +
            "ORDER BY " +
            "  c.time DESC")
    ArrayList<CommentDTO> queryCommentsByPostId(Integer postId);


    // 新增：查询帖子的一级评论（parentId为null）
    @Select("SELECT " +
            "  c.id AS commentId, " +
            "  c.text AS commentContent, " +
            "  c.time AS commentTime, " +
            "  u.tx AS avatar, " +
            "  u.nc AS nickname, " +
            "  c.userId AS userId, " +
            "  c.parentId AS parentId " +
            "FROM comment c " +
            "JOIN user u ON c.userId = u.id " +
            "WHERE c.postId = #{postId} AND c.parentId IS NULL " + // 只查一级评论
            "ORDER BY c.time DESC")
    List<CommentDTO> queryFirstLevelComments(Integer postId);

    // 新增：查询子评论（根据parentId，即被回复的评论ID）
    @Select("SELECT " +
            "  c.id AS commentId, " +
            "  c.text AS commentContent, " +
            "  c.time AS commentTime, " +
            "  u.tx AS avatar, " +
            "  u.nc AS nickname, " +
            "  c.userId AS userId, " +
            "  c.parentId AS parentId, " +
            "  pu.nc AS repliedNickname " + // 被回复者的昵称（通过父评论关联用户）
            "FROM comment c " +
            "JOIN user u ON c.userId = u.id " + // 评论者信息
            "JOIN comment pc ON c.parentId = pc.id " + // 关联父评论
            "JOIN user pu ON pc.userId = pu.id " + // 父评论的用户（被回复者）
            "WHERE c.parentId = #{parentId} " +
            "ORDER BY c.time DESC")
    List<CommentDTO> queryChildComments(Integer parentId);
}
